#include "logbuffer.h"

Logbuffer* Logbuffer::Instance () 
{
	static Logbuffer t;
	return &t; // _instance isn't needed in this case
}

Logbuffer::Logbuffer()
{
	pthread_mutex_init (&clientmessages_mutex, NULL);
	maxMessages = 5;
	msgLifetime = 3000;
	headless = false;
}

void Logbuffer::add(const std::stringstream & streamptr)
{
	add(streamptr.str());
}

void Logbuffer::add(const std::string& msgstring)
{
	if ( headless )
	{
		std::cout << msgstring << std::endl;
	}
	else
	{
		msg *Msg = new msg;
		Msg->str = msgstring;
		Msg->appeartime = Timer::Instance()->sdl_lasttime;
		Msg->len = Textprinter::Instance()->getWidth(Msg->str);
		
		pthread_mutex_lock( &clientmessages_mutex );
		messages.push_back(Msg);

		// to prevent overfilling:
		deleteExpiredMsg();
		getLongest();
		pthread_mutex_unlock( &clientmessages_mutex );
	}
}

void Logbuffer::deleteExpiredMsg()
{
	if ( !messages.empty() )
	{
		if (
			messages.size() > maxMessages
			|| ( msgLifetime > 0.0f && (Timer::Instance()->sdl_lasttime - messages[0]->appeartime) > msgLifetime )
// 			|| ( msgLifetime > 0.0f && Timer::Instance()->timediff( Timer::Instance()->lasttime, messages[0]->appeartime ) > msgLifetime )
		)
		{
			delete messages[0];
			messages.erase(messages.begin()+0);
		}
	}
}

void Logbuffer::getLongest()
{
	longestLength = 0;
	for ( unsigned int i=0; i < messages.size(); i++ )
	{
		if ( messages[i]->len > longestLength )
			longestLength = messages[i]->len;
	}
}

